package com.bstek.bdf4.builder;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @Title: 构建器
 * @Package: com.bstek.bdf4.builder
 * @Description:
 * @Author: zxq

 */
public class Builder<T>{

    private final Supplier<T> supplier;

    private  final List<Consumer<T>> lists = new ArrayList<>();

    public Builder(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public static  <T> Builder<T> builder(Supplier<T> supplier) {
        return new Builder<>(supplier);
    }

    public <R> Builder<T> with(Builder.ObjectConsumer<T,R> ocs, R r){
        Consumer<T> c= instance->ocs.accept(instance,r);
        lists.add(c);
       return this;
    }

    public  T build(){
        T t = supplier.get();
        lists.forEach(a->a.accept(t));
        return t;
    }

    @FunctionalInterface
    public interface  ObjectConsumer<T,R>{
        void accept(T t, R r);
    }

    public static void main(String[] args) {
        Builder<Su> jack = Builder.builder(Su::new).
                with(Su::setName, "jack").with(Su::setAge, 10);
        Su build = jack.build();
        System.out.println(build);
    }

    static class Su{
        private String name;
        private  Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Su{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

}
